package com.example.zuul; /**
 * @author yag
 * 文件名:2019.成都.Swagger2Markup.CLASS
 * 创建人:   yag
 * 创建时间: 2019/1/10 0010 11:24
 * 描述: ggggggggg ||  Swagger2Markup
 * 历史信息:
 * <作者>          <更新时间>                    <版本>          <版本描述>
 * yag           2019/1/10 0010 11:24         v1.0.0.0              创建基础
 */

/**
 * 〈一句话功能简述〉 类 Swagger2Markup <br> 
 * 〈ggggggggg〉
 *
 * @author yag
 * @create 2019/1/10 0010 11:24
 * @since 1.0.0
 */
import io.github.swagger2markup.*;
import io.github.swagger2markup.builder.Swagger2MarkupConfigBuilder;
import io.github.swagger2markup.markup.builder.MarkupLanguage;
import io.swagger.models.Path;
import io.swagger.models.Swagger;
import io.swagger.parser.Swagger20Parser;
import io.swagger.util.Json;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.util.CollectionUtils;

import java.io.BufferedWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

public class Swagger2Markup {

    public static void createSpringfoxSwaggerJson(MockMvc mockMvc, String contextPath, String tagDesc) throws Exception {
//        String outputDir =  "/target/generated-docs/swagger";
        String outputDir = System.getProperty("io.springfox.staticdocs.outputDir");
        //zuul路由端口
        int serverPort = 8791;
        //自定义URL地址
        String sb = "http://127.0.0.1:" + serverPort + contextPath;
//        String sb = "http://" + swagger.getHost() + ":" + serverPort + contextPath;
        MvcResult mvcResult = mockMvc.perform(get(sb+"/v2/api-docs")
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andReturn();

        MockHttpServletResponse response = mvcResult.getResponse();
        String nowJsonStr = response.getContentAsString();

        Swagger swagger = new Swagger20Parser().parse(nowJsonStr);
        swagger.setBasePath("/");
        Map<String, Path> paths = Optional.ofNullable(swagger.getPaths()).orElse(new HashMap<>());
        Map<String, Path> newPaths = new HashMap<>();
        paths.forEach((key,value) -> newPaths.put(sb + key, value));
        swagger.setPaths(newPaths);
        //自定义tag的描述
      /*  if (!CollectionUtils.isEmpty(swagger.getTags())) {
            swagger.getTags().forEach(tag -> tag.setDescription(tagDesc));
        }*/

        Files.createDirectories(Paths.get(outputDir));
        //判断是否存在其他项目的接口文档,如果存在，读取合并tag,path,definition
        if (Paths.get(outputDir,"swagger.json").toFile().exists()) {
            Swagger oldSwagger = new Swagger20Parser().parse(new String(Files.readAllBytes(Paths.get(outputDir,"swagger.json"))));
            if (!CollectionUtils.isEmpty(oldSwagger.getPaths())){
                oldSwagger.getPaths().forEach(swagger::path);
            }
            if (!CollectionUtils.isEmpty(oldSwagger.getDefinitions())){
                oldSwagger.getDefinitions().forEach(swagger::addDefinition);
            }
            if (!CollectionUtils.isEmpty(oldSwagger.getTags())){
                oldSwagger.getTags().forEach(swagger::addTag);
            }
        }
        //保存文档，用于合并到下一个项目中
        try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(outputDir, "swagger.json"), StandardCharsets.UTF_8)){
            writer.write(Json.pretty(swagger));
        }
        //json文档转换为adoc文档的配置
        Map<String, String> configMap = new HashMap<>();
        configMap.put("swagger2markup.extensions.springRestDocs.snippetBaseUri", outputDir);//输出路径
        configMap.put("swagger2markup.extensions.springRestDocs.defaultSnippets", "true");//默认值，使用代码段文件
        configMap.put(Swagger2MarkupProperties.PATHS_GROUPED_BY, GroupBy.TAGS.name());//通过tag分组
        configMap.put(Swagger2MarkupProperties.MARKUP_LANGUAGE, MarkupLanguage.ASCIIDOC.name());//生成adoc文档
        configMap.put(Swagger2MarkupProperties.OUTPUT_LANGUAGE, Language.ZH.name());//中文
        //输出文件到指定路径
        Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder(configMap).build();
        Swagger2MarkupConverter converter = Swagger2MarkupConverter.from(swagger).withConfig(config).build();
        converter.toPath(Paths.get(outputDir));

//        mockMvc.perform(post(contextPath)
//                .contentType(MediaType.APPLICATION_JSON))
//                .andDo(document("addPetUsingPOST", preprocessResponse(prettyPrint())))
//                .andExpect(status().isOk());
;
    }


}

